<?php

class User {

	/**
	 * A sql result array for our information.
	 * @var Array
	 */
	private $myInfo;

	/**
	 * Our user id
	 * @var Int
	 */
	private $myID;

	public function __construct($id) {
		assert(is_int($id));
		$this->myID = $id;
		$this->updateMyInfo();
	}

	public function updateMyInfo() {
		$sql  = 'SELECT user_displayname, user_name, user_level, user_enabled, user_email ';
		$sql .= 'FROM users ';
		$sql .= 'WHERE user_id = \'' . m($this->myID) . '\'';
		$res  = mysql_query($sql) or die(mysql_error());

		$this->myInfo = mysql_fetch_assoc($res);
	}

	public function getDisplayName() {
		return $this->myInfo['user_displayname'];
	}

	public function getUserName() {
		return $this->myInfo['user_name'];
	}

	public function getUserID() {
		return $this->myID;
	}

	public function getEmail() {
		return $this->myInfo['user_email'];
	}

	public function getLevel() {
		return $this->myInfo['user_level'];
	}

	public function isEnabled() {
		return (bool)$this->myInfo['user_enabled'];
	}

	public function getRating($addon) {
		$sql  = 'SELECT rating_rating FROM ratings WHERE user_id = ' . $this->myID;
		$sql .= ' AND addon_id = ' . ((int) $addon);
		$res  = mysql_query($sql) or print(mysql_error());

		if (mysql_num_rows($res) == 0) {
			return '-';
		} else {
			$row = mysql_fetch_assoc($res);
			return $row['rating_rating'];
		}
	}

	public function setRating($addon, $rating = '-') {
		$sql  = 'DELETE FROM ratings WHERE user_id = ' . $this->myID . ' AND ';
		$sql .= 'addon_id = ' . ((int) $addon);
		mysql_query($sql);

		if (strcmp($rating,'-') != 0) {
			$sql  = 'INSERT INTO ratings (user_id, addon_id, rating_rating) ';
			$sql .= 'VALUES (' . $this->myID . ', ' . ((int) $addon) . ', ';
			$sql .= ((int) $rating) . ')';
			mysql_query($sql);
		}

		$sql  = 'UPDATE addons SET addon_rating = (SELECT AVG(rating_rating) ';
		$sql .= 'FROM ratings WHERE addon_id = addons.addon_id) WHERE ';
		$sql .= 'addon_id = ' . ((int) $addon);
		mysql_query($sql);
	}

	public function addComment($addon, $comment) {
		$sql  = 'INSERT INTO comments (addon_id, user_id, comment_time, ';
		$sql .= 'comment_comment) VALUES (' . ((int) $addon) . ', ' . $this->myID;
		$sql .= ', ' . time() . ', \'' . m($comment) . '\')';
		mysql_query($sql);
	}

 	public function isOpenID() {
		$sql = 'SELECT user_password FROM users WHERE user_id = ' . $this->myID;
		$res = mysql_query($sql);
		$pass = mysql_result($res, 0);
		return strlen($pass) < 20;
	}
}

?>
